import { onShow } from '@dcloudio/uni-app'
import { type Ref, onBeforeUnmount, ref } from 'vue'

export default function useBottomSafe(): Ref<number> {
  const bottomSafeHeight = ref(0)
  let timerId: NodeJS.Timer
  const deviceType = ref('phone')

  const init = () => {
    uni.getSystemInfo({
      success: (res) => {
        deviceType.value = res.deviceType
        if (res.safeAreaInsets) {
          bottomSafeHeight.value = res.safeAreaInsets.bottom
        }
      },
    })
  }
  init()
  // #ifdef H5
  onShow(() => {
    if (timerId) {
      clearInterval(timerId)
    }
    // 只有手机端才需要刷新
    if (deviceType.value === 'phone') {
      timerId = setInterval(() => {
        init()
      }, 100)
    }
  })
  // #endif
  onBeforeUnmount(() => {
    if (timerId) {
      clearInterval(timerId)
    }
  })
  return bottomSafeHeight
}
